/*
 * Module name : WorkForm
 */
import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';

import TvaProductFormMixin from 'base/views/TvaProductFormMixin.js';

import ModalFormBehavior from 'base/behaviors/ModalFormBehavior.js';
import InputWidget from 'widgets/InputWidget.js';
import CheckboxWidget from 'widgets/CheckboxWidget.js';
import SelectWidget from 'widgets/SelectWidget.js';
import TextAreaWidget from 'widgets/TextAreaWidget.js';
import CatalogComponent from 'common/views/CatalogComponent.js';

import ErrorView from 'base/views/ErrorView.js';


const editTemplate = require('./templates/WorkForm.mustache');
const addTemplate = require('./templates/AddWorkForm.mustache');

const WorkForm = Mn.View.extend(TvaProductFormMixin).extend({
    partial: false,
    getTemplate() {
        let template;
        if (this.getOption('edit')) {
            template = editTemplate;
        } else {
            template = addTemplate;
        }
        return template
    },
    behaviors: [ModalFormBehavior],
    regions: {
        errors: '.errors',
        title: ".field-title",
        description: '.field-description',
        quantity: '.field-quantity',
        total_ht: '.field-total_ht',
        unity: '.field-unity',
        tva_id: '.field-tva_id',
        product_id: '.field-product_id',
        margin_rate: '.field-margin_rate',
        display_details: '.field-display_details',
    },
    // Listen to child view events
    childViewEvents: {
        'catalog:insert': 'onCatalogInsert',
    },
    // Bubble up child view events
    childViewTriggers: {
        'finish': 'data:modified',
        'change': 'data:modified'
    },
    modelEvents: {
        'change:tva_id': 'refreshTvaProductSelect',
    },
    initialize() {
        this.config = Radio.channel('config');
        this.app = Radio.channel('priceStudyApp');
        this.unity_options = this.config.request(
            'get:options',
            'workunits'
        );
        this.tva_options = this.config.request(
            'get:options',
            'tvas'
        );
        this.product_options = this.config.request(
            'get:options',
            'products',
        );
        this.all_product_options = this.config.request(
            'get:options',
            'products'
        );
    },
    showTitle() {
        this.showChildView(
            'title',
            new InputWidget({
                label: "Titre de l'ouvrage",
                description: "Titre de l'ouvrage dans le document final",
                field_name: "title",
                value: this.model.get('title'),
                required: true,
            })
        );
    },
    showDescription() {
        this.showChildView(
            'description',
            new TextAreaWidget({
                title: "Description",
                field_name: 'description',
                value: this.model.get('description'),
                tinymce: true,
            }));
    },
    showQuantity() {
        this.showChildView(
            'quantity',
            new InputWidget({
                title: "Quantité",
                field_name: "quantity",
                value: this.model.get('quantity')
            })
        );
    },
    showDisplayDetails() {
        this.showChildView(
            'display_details',
            new CheckboxWidget({
                inline_label: "Afficher le détail des prestations dans le document final",
                description: "En décochant cette case, l'ouvrage apparaîtra comme une seule ligne de prestation, sans le détail des produits",
                field_name: "display_details",
                value: this.model.get('display_details')
            })
        );
    },
    showUnity() {
        this.showChildView(
            'unity',
            new SelectWidget({
                title: "Unité",
                field_name: 'unity',
                options: this.unity_options,
                value: this.model.get('unity'),
                placeholder: 'Choisir une unité',
            })
        );
    },
    showTva() {
        this.showChildView(
            'tva_id',
            new SelectWidget({
                title: "TVA",
                field_name: 'tva_id',
                options: this.tva_options,
                id_key: 'id',
                value: this.model.get('tva_id'),
                placeholder: 'Choisir un taux de TVA',
                required: true,

            })
        );
    },
    showProduct() {
        this.product_options = this.getProductOptions(
            this.tva_options,
            this.all_product_options,
        );
        this.showChildView(
            'product_id',
            new SelectWidget({
                title: "Compte produit",
                field_name: 'product_id',
                options: this.product_options,
                id_key: 'id',
                value: this.model.get('product_id'),
                placeholder: 'Choisir un compte produit',
                required: true,

            })
        );
    },
    showMarginRate() {
        this.showChildView(
            'margin_rate',
            new InputWidget({
                title: "Coefficient de marge",
                field_name: 'margin_rate',
                value: this.model.get('margin_rate'),
                description: "Utilisé pour calculer le 'Prix intermédiaire' depuis le 'Prix de revient' selon la formule 'prix de revient / (1 - Coefficient marge)'"
            })
        );
    },
    onRender() {
        this.refreshForm();
        if (!this.getOption('edit')) {
            this.addRegion('catalogContainer', '#catalog-container');
            this.showChildView(
                'catalogContainer',
                new CatalogComponent({
                    query_params: {
                        type_: 'work'
                    },
                    url: AppOption['catalog_tree_url'],
                    multiple: true
                })
            );
        }
    },
    refreshForm() {
        this.showTitle();
        this.showDescription();
        this.showQuantity();
        this.showUnity();
        this.showDisplayDetails();
        this.showTva();
        this.showProduct();
        this.showMarginRate();
    },
    onCancelForm() {
        this.app.trigger('navigate', 'index');
    },
    templateContext() {
        return {
            title: ""
        };
    },
    onCatalogInsert(sale_products) {
        let req = this.app.request('insert:from:catalog', this.getOption("destCollection"), sale_products);
        req.then(() => {
            this.app.trigger('product:changed', this.model);
            this.triggerMethod('modal:close');
        });
    },
    onDestroyModal() {
        this.app.trigger('navigate', 'index');
    },
    onDataInvalid(model, errors) {
        this.showChildView('errors', new ErrorView({
            errors: errors
        }));
    },
    onSuccessSync() {
        this.app.trigger('product:changed', this.model);
    }
});
export default WorkForm